package com.tengju.support.application.robot;

import com.tengju.support.application.picture.PictureService;
import com.tengju.support.application.shared.ApplicationException;
import com.tengju.support.application.shared.ApplicationExceptionCode;
import com.tengju.support.domain.model.img.LineImg;
import com.tengju.support.domain.model.robot.*;
import com.tengju.support.domain.service.FeiShuRobotBaseService;
import com.tengju.support.domain.service.robotstrategy.BizRequestStrategy;
import com.tengju.user.domain.model.user.SsoUserId;
import com.tengju.user.domain.model.user.StaffSimpleInfo;
import com.tengju.user.domain.service.DepartmentExternalService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class FeiShuRobotService {

    private final ApplicationContext applicationContext;
    private final FeiShuRobotBaseService feiShuRobotBaseService;
    private final DepartmentExternalService departmentExternalService;
    private final PictureService pictureService;
    @Value("${feishu.robot.rule}")
    private String ruleContext;
    @Value("${feishu.wx.robot.rule}")
    private String wxRuleContext;

    @Value("${feishu.robot.appId}")
    private String appId;
    @Value("${feishu.robot.appSecret}")
    private String appSecret;
    @Value("${feishu.wx.robot.appId}")
    private String wxAppId;
    @Value("${feishu.wx.robot.appSecret}")
    private String wxAppSecret;

    /**
     * 机器人回复
     */
    public void feedBack(FeiShuRobotConversation conversation) {
        FeiShuRobotSendMsgV2Form sendMsgForm;

        //获取机器人发送消息token
        String accessToken = feiShuRobotBaseService.getAccessToken(appId, appSecret);
        if (StringUtils.isEmpty(accessToken)) {
            log.error("飞书机器人获取token失败");
        }

        if (conversation == null || conversation.getEvent() == null) {
            log.error("飞书机器人收到消息为空，eventId:{}", Optional.ofNullable(conversation).map(FeiShuRobotConversation::getUuid).orElse(""));
            return;
        }

        // 获取会话id
        String openChatId = conversation.getEvent().getOpen_chat_id();

        try {
            String text = conversation.getEvent().getText_without_at_bot();
            String employeeId = conversation.getEvent().getEmployee_id();

            ReqParam reqParam = ReqParamFactory.create(text, employeeId);

            if (reqParam == null) {
                //robot发送协议规则信息
                sendRuleMsg(conversation, accessToken);
                return;
            }

            BizRequestStrategy strategy = (BizRequestStrategy) applicationContext
                    .getBean(reqParam.getType().getStrategy());

            //请求业务接口
            FeiShuMsgData feiShuMsgData = strategy.reqBizMethod(reqParam);

            //机器人发送消息
            if (feiShuMsgData.getMsgType() == FeiShuRobotSendMsgType.IMAGE) {
                FeiShuRobotSendImMsgImgContent imgContent = new FeiShuRobotSendImMsgImgContent();
                if (feiShuMsgData.getData() instanceof LineImg) {
                    //上传图片
                    LineImg lineImg = (LineImg) feiShuMsgData.getData();
                    File file = pictureService.generateLineImgStream(lineImg);
                    String imageKey = uploadImage(ImageType.MESSAGE, file, accessToken);
                    imgContent.setImage_key(imageKey);
                }

                sendMsgForm = new FeiShuRobotSendMsgV2Form(
                        accessToken,
                        openChatId,
                        FeiShuRobotImMsgReceiveIdType.CHAT_ID,
                        FeiShuRobotSendMsgType.IMAGE,
                        imgContent);

            } else {
                sendMsgForm = getFeiShuRobotSendMsgV2Form(openChatId, accessToken, feiShuMsgData);
            }

        } catch (Exception e) {
            log.error("飞书机器人回复失败", e);
            FeiShuRobotSendImMsgTextContent textContent = new FeiShuRobotSendImMsgTextContent();
            textContent.setText("系统异常，" + e.getMessage());
            sendMsgForm = new FeiShuRobotSendMsgV2Form(
                    accessToken,
                    conversation.getEvent().getOpen_chat_id(),
                    FeiShuRobotImMsgReceiveIdType.CHAT_ID,
                    FeiShuRobotSendMsgType.TEXT,
                    textContent);
        }
        feiShuRobotBaseService.sendMsgV2(sendMsgForm);

    }

    /**
     * 企业微信机器人回复
     */
    public void wxFeedBack(FeiShuRobotConversation conversation) {
        FeiShuRobotSendMsgV2Form sendMsgForm;

        //获取机器人发送消息token
        String accessToken = feiShuRobotBaseService.getAccessToken(wxAppId, wxAppSecret);
        if (StringUtils.isEmpty(accessToken)) {
            log.error("企业微信机器人获取token失败");
        }

        if (conversation == null || conversation.getEvent() == null) {
            log.error("企业微信机器人收到消息为空，eventId:{}", Optional.ofNullable(conversation).map(FeiShuRobotConversation::getUuid).orElse(""));
            return;
        }

        // 获取会话id
        String openChatId = conversation.getEvent().getOpen_chat_id();

        try {
            String text = conversation.getEvent().getText_without_at_bot();
            String employeeId = conversation.getEvent().getEmployee_id();

            ReqParam reqParam = ReqParamFactory.create(text, employeeId);
            if (reqParam == null) {
                //robot发送协议规则信息
                sendWxRuleMsg(conversation, accessToken);
                return;
            }

            BizRequestStrategy strategy = (BizRequestStrategy) applicationContext
                    .getBean(reqParam.getType().getStrategy());

            //请求业务接口
            FeiShuMsgData feiShuMsgData = strategy.reqBizMethod(reqParam);

            //机器人发送消息
            sendMsgForm = getFeiShuRobotSendMsgV2Form(openChatId, accessToken, feiShuMsgData);
        } catch (Exception e) {
            log.error("企业微信机器人回复失败", e);
            FeiShuRobotSendImMsgTextContent textContent = new FeiShuRobotSendImMsgTextContent();
            textContent.setText("系统异常，" + e.getMessage());
            sendMsgForm = new FeiShuRobotSendMsgV2Form(
                    accessToken,
                    openChatId,
                    FeiShuRobotImMsgReceiveIdType.CHAT_ID,
                    FeiShuRobotSendMsgType.TEXT,
                    textContent);
        }
        feiShuRobotBaseService.sendMsgV2(sendMsgForm);
    }

    /**
     * 构建普通文本消息表单
     *
     * @param openChatId    会话id
     * @param accessToken   机器人凭证
     * @param feiShuMsgData 消息
     * @return 普通文本消息表单
     */
    private FeiShuRobotSendMsgV2Form getFeiShuRobotSendMsgV2Form(String openChatId, String accessToken, FeiShuMsgData feiShuMsgData) {
        FeiShuRobotSendMsgV2Form sendMsgForm;
        FeiShuRobotSendImMsgTextContent textContent = new FeiShuRobotSendImMsgTextContent();

        if (StringUtils.isEmpty(feiShuMsgData.getData())) {
            textContent.setText("数据为空");
        } else {
            textContent.setText((String) feiShuMsgData.getData());
        }
        sendMsgForm = new FeiShuRobotSendMsgV2Form(
                accessToken,
                openChatId,
                FeiShuRobotImMsgReceiveIdType.CHAT_ID,
                feiShuMsgData.getMsgType(),
                textContent);
        return sendMsgForm;
    }

    private void sendRuleMsg(FeiShuRobotConversation conversation, String accessToken) {

        FeiShuRobotSendMsgForm sendMsgForm = new FeiShuRobotSendMsgForm(accessToken, conversation.getEvent().getOpen_id(),
                conversation.getEvent().getOpen_chat_id(), conversation.getEvent().getChat_type(),
                conversation.getEvent().getRoot_id(), conversation.getEvent().getMsg_type(), ruleContext);
        feiShuRobotBaseService.sendMsg(sendMsgForm);
    }

    private void sendWxRuleMsg(FeiShuRobotConversation conversation, String accessToken) {
        FeiShuRobotSendMsgForm sendMsgForm = new FeiShuRobotSendMsgForm(accessToken, conversation.getEvent().getOpen_id(),
                conversation.getEvent().getOpen_chat_id(), conversation.getEvent().getChat_type(),
                conversation.getEvent().getRoot_id(), conversation.getEvent().getMsg_type(), wxRuleContext);
        feiShuRobotBaseService.sendMsg(sendMsgForm);
    }

    public Boolean sendMsg(SsoUserId ssoUserId, FeiShuRobotSendMsgType sendMsgType, FeiShuRobotSendImMsgContent content) {

        //获取机器人发送消息token
        String accessToken = feiShuRobotBaseService.getAccessToken(appId, appSecret);
        if (StringUtils.isEmpty(accessToken)) {
            log.error("飞书机器人获取token失败");
            return Boolean.FALSE;
        }

        StaffSimpleInfo staffSimpleInfo = departmentExternalService.getStaffSimpleInfoBySsoUserId(ssoUserId);
        if (staffSimpleInfo == null) {
            log.error("员工信息不存在 {}", ssoUserId.getValue());
            return Boolean.FALSE;
        }
        if (StringUtils.isEmpty(staffSimpleInfo.getEmail())) {
            log.error("员工邮箱为空");
            return Boolean.FALSE;
        }

        FeiShuRobotSendMsgV2Form sendMsgForm = new FeiShuRobotSendMsgV2Form(
                accessToken,
                staffSimpleInfo.getEmail(),
                FeiShuRobotImMsgReceiveIdType.EMAIL,
                sendMsgType,
                content);
        return feiShuRobotBaseService.sendMsgV2(sendMsgForm);
    }

    public String uploadImage(ImageType imageType, File file, String accessToken) {

        try {
            FeiShuRobotUploadImgForm feiShuRobotUploadImgForm =
                    new FeiShuRobotUploadImgForm(accessToken, imageType, file);

            return feiShuRobotBaseService.uploadImage(feiShuRobotUploadImgForm);
        } catch (Exception e) {
            log.error("uploadImage error:", e);
            throw ApplicationException.error(ApplicationExceptionCode.INVALID_DATA, "图片上传飞书失败");

        }

    }
}
